package com.sskj.hhhjys;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;

import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.hhhjys.bean.Stock;
import com.sskj.hhhjys.util.DataUtil;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.util.TimeFormatUtil;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/05/10
 */
public class ChartFragment extends BaseFragment<ChartPresenter> {

    @BindView(R.id.charView)
    KChartView charView;
    private String goodsType;
    private String code;

    private boolean mIsMinute;
    private KChartAdapter mAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_chart;
    }

    @Override
    public ChartPresenter getPresenter() {
        return new ChartPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        code = getArguments().getString("code");
        goodsType = getArguments().getString("goodsType");
        mIsMinute = getArguments().getBoolean("isMinute");
        charView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.app_chart_bg));
        charView.showLoading();
        charView.setDrawTabView(true);
        charView.setMainUpColor(R.color.app_market_up);  // 设置k线颜色 涨
        charView.setMainDownColor(R.color.app_marekt_down); // 设置k线颜色 跌
        charView.setGridRows(4);
        charView.getmCurrentPricePaint().setTextSize(30);
        charView.setGridColumns(4);
        charView.setVolumeMaGone(true);
        if (mIsMinute) {
            charView.setDrawMinuteStyle(true);
            charView.setDateTimeFormatter(new TimeFormatter());
        } else {
            charView.setDateTimeFormatter(new DateLFormatter());
        }
        mAdapter = new KChartAdapter();
        charView.setAdapter(mAdapter);
    }


    @Override
    public void initData() {
        mPresenter.getStockInfo(goodsType, code);
    }

    /**
     * @param code 币种编码
     * @return
     */
    public static ChartFragment newInstance(String code, String goodsType, boolean isMinute) {
        ChartFragment chartFragment = new ChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString("code", code);
        bundle.putString("goodsType", goodsType);
        bundle.putBoolean("isMinute", isMinute);
        chartFragment.setArguments(bundle);
        return chartFragment;
    }

    public void setChart(List<Stock> stockList) {

        if (charView != null) {
            charView.hideLoading();
            if (stockList == null)
                return;
            Collections.reverse(stockList);
            DataUtil.calculate(stockList);
            mAdapter.getDatas().clear();
            mAdapter.updateData(stockList);
        }
    }

    public KChartView getKChartView() {
        return charView;
    }

    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */
    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            return new Date(datas.get(position).getDate());
        }

        /**
         * 向头部添加数据
         */
        public void addNewData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyItemRangeInsertedToLast();
            }
        }


        /**
         * 向尾部添加数据
         */
        public void updateData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.clear();
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         */
        public void changeLastItemClosePrice(float closePrice) {
            notifyLastItemChanged(closePrice);
        }

    }

    /**
     * 长链接  更新当前分时图
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals(code) && mAdapter.getCount() > 0) {
            if (isLastNewData(data)) {
                mAdapter.changeLastItemClosePrice(new BigDecimal(data.getPrice()).floatValue());
            } else {
                mPresenter.getStockInfo(goodsType, code);
            }
        }
    }

    private boolean isLastNewData(CoinBean data) {
        try {
            String time = data.getDate() + " " + data.getTime();
            Date newDate = TimeFormatUtil.SF_FORMAT_E.parse(time);
            long compareTime = newDate.getTime();
            return isSameTime(compareTime);
        } catch (ParseException e) {
            return false;
        }
    }

    private boolean isSameTime(long compareTime) {
        long dividerTime = 1;
        switch (goodsType) {
            case "minute":
                dividerTime = 1000 * 60;
                break;
            case "minute15":
                dividerTime = 1000 * 60 * 15;
                break;
            case "minute30":
                dividerTime = 1000 * 60 * 30;
                break;
            case "minute60":
                dividerTime = 1000 * 60 * 60;
                break;
            case "day":
                dividerTime = 1000 * 60 * 60 * 24;
                break;
        }
        return compareTime / dividerTime == mAdapter.getDatas().get(mAdapter.getCount() - 1).getDate() / dividerTime;
    }


}
